import {Component} from "react";
import {Modal, Provider, Toast} from "@ant-design/react-native";
import {apiDomain, postData} from "../../common/api";
import {Dimensions, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {observer} from "mobx-react";
import cartStatus from "../../common/cartStatus";
import userStatus from "../../common/userStatus";

@observer
export default class Cart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            list: [],
            userInfo: {}
        }
    }

    componentWillUnmount = () => {
        this.setState = (state, callback) => {
            return;
        };
    }

    componentDidMount() {
        const loading = Toast.loading('loading')
        postData(apiDomain + "/Index/getUserInfo", {
            id: userStatus.userStatus.id
        }).then(res => {
            if (res.code === 200) {
                this.setState({
                    userInfo: res.data
                })
            } else {
                Modal.alert('Error', res.msg, [
                    {text: 'OK'},
                ])
            }
        }).finally(() => {
            Toast.remove(loading)
        })
    }

    add(o) {
        o.num = o.num + 1
        cartStatus.calcSum()
    }

    reduce(o) {
        if (o.num > 1) {
            o.num = o.num - 1
            cartStatus.calcSum()
        }
    }

    delete(o) {
        cartStatus.cartList.splice(
            cartStatus.cartList.findIndex(i => {
                return i === o
            }), 1)
    }

    getQuotation() {
        Modal.prompt('Send quotation', 'Please input email', [
            {
                text: 'Ok',
                onPress: (value) => {
                    this.sendQuotation(value)
                }
            },
            {
                text: 'Cancel'
            }
        ])
    }

    sendQuotation(email) {
        const loading = Toast.loading('loading')
        let orderData = cartStatus.cartList.map(o => {
            return {
                id: o.id,
                num: o.num
            }
        })
        postData(apiDomain + "/Index/getQuotation", {
            list: orderData,
            userId: userStatus.userStatus.id,
            promotionCode: cartStatus.promotionCode,
            email: email
        }).then(res => {
            if (res.code === 200) {
                Modal.alert('Success', "Send quotation success!", [
                    {text: 'OK'},
                ])
            } else {
                Modal.alert('Error', res.msg, [
                    {text: 'OK'},
                ])
            }
        }).finally(() => {
            Toast.remove(loading)
        })
    }

    createOrder() {
        const loading = Toast.loading('loading')
        const url = apiDomain + "/Index/createOrder"
        let orderData = cartStatus.cartList.map(o => {
            return {
                id: o.id,
                num: o.num
            }
        })
        postData(url, {
            list: orderData,
            userId: userStatus.userStatus.id,
            promotionCode: cartStatus.promotionCode
        }).then(res => {
            if (res.code === 200) {
                console.log('create success', res.data)
                Modal.alert('Success', "Create order success!", [
                    {text: 'OK'},
                ])
            } else {
                Modal.alert('Error', res.msg, [
                    {text: 'OK'},
                ])
            }
        }).finally(() => {
            Toast.remove(loading)
        })
    }

    inputPromotionCode() {
        Modal.prompt('Promotion code', 'Please input your promotion code', [
            {
                text: 'ok',
                onPress: (value) => {
                    const loading = Toast.loading('loading')
                    postData(apiDomain + "/Index/getPromotion", {
                        code: value
                    }).then(res => {
                        if (res.code === 200) {
                            cartStatus.setPromotion(res.data.promotion)
                            cartStatus.setPromotionCode(value)
                            cartStatus.calcSum()
                        } else {
                            Modal.alert('Error', res.msg, [
                                {text: 'OK'},
                            ])
                        }
                    }).finally(() => {
                        Toast.remove(loading)
                    })
                }
            },
            {
                text: 'cancel'
            }
        ])
    }

    render() {
        return (
            <View style={styles.provider}>
                <ScrollView
                    style={styles.container}
                    automaticallyAdjustContentInsets={false}
                    showsHorizontalScrollIndicator={false}
                    showsVerticalScrollIndicator={false}
                >
                    {
                        cartStatus.cartList.map(o => {
                            return (
                                <View style={styles.item} key={o.id}>
                                    <View style={styles.coverView}>
                                        <Image source={{uri: o.info.cover}} style={styles.cover}/>
                                    </View>
                                    <View style={styles.info}>
                                        <View style={{justifyContent: 'space-between', flexDirection: 'row', alignItems: 'flex-end'}}>
                                            <View>
                                                <Text style={styles.title}>{o.info.name}</Text>
                                                <Text style={styles.content}>Remains {o.info.stock}</Text>
                                            </View>
                                            <Text style={styles.price}>${o.info.salesPrice}</Text>
                                            <View style={styles.operation}>
                                                <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between'}}>
                                                    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
                                                        <TouchableOpacity style={styles.addBtn}
                                                                          onPress={() => this.add(o)}>
                                                            <Image source={require('../../img/add.png')} style={{width: 30, height: 30}} />
                                                        </TouchableOpacity>
                                                        <Text style={styles.num}>{o.num}</Text>
                                                        <TouchableOpacity style={styles.addBtn}
                                                                          onPress={() => this.reduce(o)}>
                                                            <Image source={require('../../img/reduce.png')} style={{width: 30, height: 30}} />
                                                        </TouchableOpacity>
                                                    </View>
                                                    <TouchableOpacity style={styles.deleteBtn} onPress={() => this.delete(o)}>
                                                        <Image source={require('../../img/delete2.png')} style={{width: 30, height: 30}}/>
                                                    </TouchableOpacity>
                                                </View>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            )
                        })
                    }
                </ScrollView>
                <View style={styles.btnView}>
                    <TouchableOpacity style={styles.cart} onPress={() => this.inputPromotionCode()}>
                        <Text style={styles.cartText}>
                            {
                                cartStatus.promotion === 0 ? (
                                    <Text>Promotion Code</Text>
                                ) : (
                                    <Text>Promotion: {cartStatus.promotion}%</Text>
                                )
                            }
                        </Text>
                    </TouchableOpacity>
                    <Text style={styles.sum}>${cartStatus.cartSum}</Text>
                </View>
                <View style={styles.btnView}>
                    <TouchableOpacity style={styles.cart} onPress={() => this.getQuotation()}>
                        <Text style={styles.cartText}>Get Quotation</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.cart} onPress={() => this.createOrder()}>
                        <Text style={styles.cartText}>Confirm</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}


const {width, height} = Dimensions.get('window');
const {screenWidth, screenHeight} = Dimensions.get('screen');

const styles = StyleSheet.create({
    provider: {
        width: screenWidth,
        height: screenHeight,
        flex: 1
    },
    container: {
        flex: 1,
        backgroundColor: '#ffffff',
        width: screenWidth,
        height: screenHeight
    },
    item: {
        paddingLeft: 20,
        paddingRight: 20,
        paddingTop: 10,
        paddingBottom: 10,
        borderColor: '#f5f6f5',
        borderTopWidth: 1,
        borderBottomWidth: 1,
        marginTop: 30,
    },
    title: {
        fontSize: 20,
        fontWeight: 'bold'
    },
    content: {
        fontSize: 13,
        marginTop: 5
    },
    info: {
        flex: 1,
        flexDirection: 'column',
        marginTop: 10
    },
    cover: {
        width: 0.9 * width,
        height: 0.4 * width
    },
    coverView: {
    },
    mainTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        paddingTop: 20
    },
    price: {
        fontSize: 18,
        marginTop: 5,
        fontWeight: 'bold'
    },
    operation: {
        marginTop: 10
    },
    addBtn: {
        borderStyle: "solid",
        width: 30,
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
    },
    num: {
        marginLeft: 5,
        marginRight: 5,
        justifyContent: 'center',
    },
    deleteBtn: {
        width: 30,
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 5
    },
    delete: {
        width: 15,
        height: 15
    },

    btnView: {
        paddingTop: 10,
        paddingBottom: 10,
        width: screenWidth,
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'space-between',
        borderTopColor: 'rgb(216, 216, 216)',
        borderStyle: 'solid',
        borderTopWidth: 1
    },
    cart: {
        width: 0.4 * width,
        backgroundColor: 'rgb(0, 21, 41)',
        paddingTop: 10,
        paddingBottom: 10,
        justifyContent: 'center',
        alignItems: 'center',
        textAlign: 'center',
    },
    cartText: {
        color: '#ffe700',
        textAlign: 'center'
    },
    sum: {
        color: 'rgb(0, 21, 41)',
        fontSize: 24,
        fontWeight: 'bold',
        width: 0.6 * screenWidth,
    },
    addressView: {
        paddingLeft: 20,
        paddingRight: 20,
        paddingTop: 10,
        paddingBottom: 10,
        backgroundColor: '#f5f6f5',
        borderRadius: 10,
        marginTop: 20
    },
    userInfoView: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    promotionView: {
        paddingTop: 6,
        paddingBottom: 6,
        width: screenWidth,
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: '#efefef',
        borderTopColor: 'rgb(216, 216, 216)',
        borderStyle: 'solid',
        borderTopWidth: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
});
